package com.insight.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.insight.common.constant.CommonConstant;
import com.insight.common.util.oConvertUtils;
import com.insight.modules.system.entity.SysAnnouncement;
import com.insight.modules.system.entity.SysAnnouncementSend;
import com.insight.modules.system.mapper.SysAnnouncementMapper;
import com.insight.modules.system.mapper.SysAnnouncementSendMapper;
import com.insight.modules.system.mapper.SysUserMapper;
import com.insight.modules.system.service.ISysAnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 系统通告表
 * @Author: jeecg-boot
 * @Date: 2019-01-02
 * @Version: V1.0
 */
@Service
public class SysAnnouncementServiceImpl extends ServiceImpl<SysAnnouncementMapper, SysAnnouncement> implements ISysAnnouncementService {

    @Resource
    private SysAnnouncementMapper sysAnnouncementMapper;
    @Resource
    private SysAnnouncementSendMapper sysAnnouncementSendMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 保存公告，同时为公告指定的用户插入公告发送记录
     * @param sysAnnouncement 公告实体
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAnnouncement(SysAnnouncement sysAnnouncement) {
        // 1. 保存公告主表记录
        sysAnnouncementMapper.insert(sysAnnouncement);

        List<String> userIds;
        // 2. 判断消息类型，如果是发送给所有用户，则查询所有用户ID，否则使用指定的用户ID集合
        if (sysAnnouncement.getMsgType().equals(CommonConstant.MSG_TYPE_ALL)) {
            userIds = sysUserMapper.getAllUserId();
        } else {
            String userId = sysAnnouncement.getUserIds();
            userIds = Arrays.asList(userId.split(","));
        }

        // 3. 为每个用户插入公告发送表，标记为未读
        String anntId = sysAnnouncement.getId();
        for (String id : userIds) {
            SysAnnouncementSend announcementSend = new SysAnnouncementSend();
            announcementSend.setAnntId(anntId);
            announcementSend.setUserId(id);
            announcementSend.setReadFlag(CommonConstant.NO_READ_FLAG);
            sysAnnouncementSendMapper.insert(announcementSend);
        }
    }

    /**
     * 更新公告信息，同时更新公告发送用户列表（只处理指定用户类型的消息）
     * @param sysAnnouncement 公告实体
     * @return 是否更新成功
     */
    @Transactional
    @Override
    public boolean upDateAnnouncement(SysAnnouncement sysAnnouncement) {
        // 1. 更新公告主表信息
        sysAnnouncementMapper.updateById(sysAnnouncement);

        String userId = sysAnnouncement.getUserIds();
        // 只处理针对指定用户的公告类型更新
        if (oConvertUtils.isNotEmpty(userId) && sysAnnouncement.getMsgType().equals(CommonConstant.MSG_TYPE_UESR)) {
            // 注意：这里去掉了 userId 最后一个字符，防止尾部逗号影响
            String[] userIds = userId.substring(0, (userId.length() - 1)).split(",");
            String anntId = sysAnnouncement.getId();
            Date refDate = new Date();

            // 2. 补充新的接收用户（之前没有的插入）
            for (int i = 0; i < userIds.length; i++) {
                LambdaQueryWrapper<SysAnnouncementSend> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SysAnnouncementSend::getAnntId, anntId);
                queryWrapper.eq(SysAnnouncementSend::getUserId, userIds[i]);

                List<SysAnnouncementSend> announcementSends = sysAnnouncementSendMapper.selectList(queryWrapper);
                if (announcementSends.size() <= 0) {
                    SysAnnouncementSend announcementSend = new SysAnnouncementSend();
                    announcementSend.setAnntId(anntId);
                    announcementSend.setUserId(userIds[i]);
                    announcementSend.setReadFlag(CommonConstant.NO_READ_FLAG);
                    announcementSend.setReadTime(refDate);
                    sysAnnouncementSendMapper.insert(announcementSend);
                }
            }

            // 3. 删除公告中不再包含的用户发送记录
            Collection<String> delUserIds = Arrays.asList(userIds);
            LambdaQueryWrapper<SysAnnouncementSend> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.notIn(SysAnnouncementSend::getUserId, delUserIds);
            queryWrapper.eq(SysAnnouncementSend::getAnntId, anntId);
            sysA

